package com.king.juc.n8.jucdemo.cyclicbarrier;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.king.juc.utils.ThreadUtil.sleep;

/**
 * CyclicBarrier（循环栅栏）
 *
 * @author king
 * @date 2020/12/13 17:55
 */
@Slf4j(topic = "c.CyclicBarrierTest")
public class CyclicBarrierTest {
    public static void main(String[] args) {
        method1();
    }

    /**
     * 基本使用
     */
    private static void method1() {
        ExecutorService service = Executors.newFixedThreadPool(2);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.debug("task1, task2, finish...");
        });

        for (int i = 0; i < 3; i++) {
            service.submit(() -> {
                log.debug("task1 begin...");
                sleep(1);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    log.error("error: ", e);
                }
            });

            service.submit(() -> {
                log.debug("task2 begin...");
                sleep(2);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    log.error("error: ", e);
                }
            });
        }
        service.shutdown();
    }
}
